package jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.text.SimpleDateFormat;

/*
  Ejemplos de Metadata
*/
public class Metadata {
    public static void main(String[] args) {
        String driver = "org.gjt.mm.mysql.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        
        try {
            Class.forName(driver);
//            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        } catch (ClassNotFoundException ex) {
            System.out.println("Driver incorrecto/Driver no en classpath: " + ex);
            return;
        }
        Connection con = null;
        try {
            con = DriverManager.getConnection(url, "root", "12345678");

            Statement st = con.createStatement();
            String consulta  ="select * from Persona";
            ResultSet rs = st.executeQuery(consulta);
            
            ResultSetMetaData rsmd = rs.getMetaData();
            System.out.println(rsmd.getColumnCount());
            System.out.println(rsmd.getColumnName(1));
            System.out.println(rsmd.getColumnDisplaySize(1));
            System.out.println(rsmd.getColumnType(1));
            System.out.println(rsmd.getColumnTypeName(1));
            System.out.println(rsmd.getPrecision(1));
            while(rs.next()){

                String nombre = rs.getString("nombre");
                double sueldo = rs.getDouble("sueldo");
                Date fecha = rs.getDate("fechaNacimiento"); 
                SimpleDateFormat sdf = new SimpleDateFormat("dd  MM  yyyy");
                System.out.println(nombre+ " " + sueldo + " " +sdf.format(fecha));
            }

            DatabaseMetaData dmd = con.getMetaData();
            
            ResultSet tablas = dmd.getTables(null, null, "%", null);

            while(tablas.next()){
                String nombre = tablas.getString("TABLE_NAME");
                System.out.println(nombre);
            }
            
            ResultSet columnas = dmd.getColumns(null,null,"Persona","%");

            while(columnas.next()){
                String tabla = columnas.getString("TABLE_NAME");
                String nombre = columnas.getString("COLUMN_NAME");
                System.out.println(tabla+"."+nombre);
            }
            
            
        } catch (Exception ex) {
            System.out.println("ERROR: " + ex);
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception ex) {
                }
            }
        }


    }
}
